package websocket

import (
	"encoding/json"
	"runtime/debug"
)

var (
	routers = make(map[string]EventHandler)
)

// EventHandler 消息事件处理器
type EventHandler func(client *Client, req *WsRequest)

// EventHandlerRouters 消息事件处理器
type EventHandlerRouters map[string]EventHandler

// RegisterRouter 注册 websocket 中事件路由处理器，用于处理对应的消息
func RegisterRouter(handlers EventHandlerRouters) {
	for k, f := range handlers {
		if _, ok := routers[k]; ok {
			Logger().Fatalf(ctx, "websocket router register repeat [%s]", k)
			return
		}
		routers[k] = f
	}
}

func EventHandleExec(client *Client, message []byte) {
	defer func() {
		if r := recover(); r != nil {
			Logger().Warningf(ctx, "handlerMsg recover, err:%+v, stack:%+v", r, string(debug.Stack()))
		}
	}()
	var request *WsRequest
	if err := json.Unmarshal(message, &request); err != nil {
		Logger().Warningf(ctx, "websocket data parse err:%+v, message:%+v", err, message)
		return
	}

	if request.Event == "" {
		Logger().Warning(ctx, "websocket.event is empty")
		return
	}

	fun, ok := routers[request.Event]
	if !ok {
		Logger().Warning(ctx, "event unregister")
		return
	}

	fun(client, request)
}
